import { useState } from 'react'
import logo from './logo.svg'
import './App.css'

function App() {


  return (
    <div className="App">
      <Input></Input>
      <Select></Select>
      <Moreselect></Moreselect>
    </div>
  )
}

// 实现input输入 双向绑定
function Input() {
  const [inputname, setInputname] = useState('jhq')
  const onChange = (e) => {

    setInputname(e.target.value)
  }

  return (
    <>
      <input type="text" value={inputname} onChange={onChange} />
      <h1>state状态数据：{inputname}</h1>
    </>
  )
}

// 实现单选框  双向绑定(非受控组件变为受控组件)
function Select() {
  const [selectname, setSelectname] = useState('cute');
  const handleChange = (event) => {
    setSelectname(event.target.value);
  };
  const handleSubmit = (event) => {
    alert('你今日相亲对象的类型是: ' + selectname);
    event.preventDefault();
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <label>
          你今日相亲对象的类型是:
          <select value={selectname} onChange={handleChange}>
            <option value="sunshine">阳光</option>
            <option value="handsome">帅气</option>
            <option value="cute">可爱</option>
            <option value="reserved">高冷</option>
          </select>
        </label>
        <h1>state中select的状态为:{selectname}</h1>
        <input type="submit" value="提交" />
      </form>
    </>
  )
}

// 实现多选框
function Moreselect() {
  let [moreselectname, setMoreSelectname] = useState(['cute']);
  const handleChange = (e) => {
    const val = e.target.value;
    const oldValue = moreselectname;
    const i = moreselectname.indexOf(val);
    // 对新旧数组进行合并
    const newValue = i > -1 ? [...oldValue].splice(i, 1) : [...oldValue, val];
    setMoreSelectname(newValue)
  }
  const handleSubmit = (e) => {
    alert('你今日相亲对象的类型是: ' + moreselectname);
    e.preventDefault();
  }
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          你今日相亲对象的类型是:
          {/* 如果multiple为true，则 value 必须为一个数组 */}
          <select multiple={true} value={moreselectname} onChange={handleChange} >

            <option value="sunshine">阳光</option>
            <option value="handsome">帅气</option>
            <option value="cute">可爱</option>
            <option value="reserved">高冷</option>
          </select>
        </label>
        <input type="submit" value="提交" />
      </form>
      <h2>多选框数据状态为:{moreselectname}</h2>
    </div>
  )
}
export default App
